package com.easytopit.demo.spring.mvc.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.easytopit.demo.spring.mvc.domain.JSONResult;
import com.easytopit.demo.spring.mvc.domain.User;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.security.AnyTypePermission;
import com.thoughtworks.xstream.security.NoTypePermission;

@RestController
@RequestMapping("/xml")
public class XstreamController {

	@GetMapping("/get")
	public User get() {// 发送:User -> JSON -> 序列化
		User user = new User();
		user.setId(1);
		user.setName("ok");
		return user;
	}

	@PostMapping("/add") // 接收: JSON -> User -> 反序列化
	public JSONResult add(User user) {
		return new JSONResult(1, user);
	}
	
	public static void main(String[] args) {
		// 手工使用
		XStream xStream = new XStream(new DomDriver());
		
		// 安全性
		xStream.addPermission(NoTypePermission.NONE);
		xStream.addPermission(AnyTypePermission.ANY);
		
		// 取别名
		xStream.alias("user", User.class);
		
		// User -> XML
		User user = new User();
		user.setId(1);
		user.setName("ok");
		String xml = xStream.toXML(user);
		System.out.println("User -> XML:\n" + xml);
		
		// XML -> User
		User parseObject = (User) xStream.fromXML(xml);
		System.out.println("XML -> User:"+parseObject);
	}
}
